<template>
  <div style="padding:30px;">
    <Breadcrumb />
    <el-card class="box-card" style="margin-top:15px;">
      <el-alert
        title="只允许为第三级分类设置相关参数！"
        type="warning"
        show-icon
        :closable="false"
      />
      <el-row style="margin: 20px 0 40px 0">
        选择商品分类：
        <el-cascader
          ref="check"
          v-model="classify"
          :options="goodsClassify"
          :props="defaults"
          @focus="getGoodsClassify"
          @blur="onBlur"
          @change="handleChange"
        />
      </el-row>
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="first">
          <comment-data-plan title="添加参数" :classify-data="classifyData" :cat-id="catId" :disable="disable" @onSuccess="onSuccess" />
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="second">
          <comment-data-plan title="添加属性" :classify-data="classifyData" :cat-id="catId" :disable="disable" @onSuccess="onSuccess" />
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script>
import { goodsClassify, queryClassifyById } from '@/api/classify.js'
import CommentDataPlan from './components/CommentDataPlan.vue'

export default {
  name: 'Classify',
  components: {
    CommentDataPlan
  },
  data() {
    return {
      classify: [],
      goodsClassify: [], // 下拉框数据
      defaults: {
        expandTrigger: 'hover',
        label: 'cat_name',
        value: 'cat_id'
      },
      activeName: 'first',
      // 控制添加按钮是否被禁用状态
      disable: true,
      catId: 0,
      tabIndex: 0,
      classifyData: []
    }
  },
  created() {

  },

  methods: {
    // 当下拉框获得焦点时 获取数据
    async  getGoodsClassify() {
      const res = await goodsClassify()
      this.goodsClassify = res
    },
    handleClick(tab, event) {
      if (tab.index === '0') {
        this.tabIndex = 0
      } else {
        this.tabIndex = 1
      }
      if (this.classify.length) {
        this.onBlur()
      }
    },
    async onBlur() {
      if (!this.catId) {
        this.disable = true
      } else {
        this.disable = false
      }
      if (this.tabIndex === 0) {
        const res = await queryClassifyById(this.catId, 'many')
        this.classifyData = res
      } else {
        const res = await queryClassifyById(this.catId, 'only')
        this.classifyData = res
      }
      this.classifyData.forEach(item => {
        if (item.attr_vals.length) {
          item.attr_vals = item.attr_vals.split(' ')
        } else {
          item.attr_vals = []
        }
      })
    },
    handleChange() {
      const res = this.$refs.check.getCheckedNodes()
      this.catId = res[0].data.cat_id
      this.onBlur()
    },
    // 添加成功后重新刷新下页面
    onSuccess() {
      this.onBlur()
    }
  }
}
</script>

<style scoped lang='less'>

</style>

